58.3 Custom context path
58.3 自定义上下文路径
如果服务器的上下文路径没有配置为/
,则云计算端点在应用程序的根上不可用。例如,如果配置为server.servlet.context-path=/foo
, 则Cloud Foundry的端点位于/foo/cloudfoundryapplication/*
。
如果你希望云计算端点始终在/cloudfoundryapplication/*
上可用,无论服务器的上下文路径如何,你都需要在应用程序中显式地配置它。配置将根据使用的web服务器而有所不同。对于Tomcat,可以添加以下配置:
@Bean
public TomcatServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory() {
@Override
protected void prepareContext(Host host,
ServletContextInitializer[] initializers) {
super.prepareContext(host, initializers);
StandardContext child = new StandardContext();
child.addLifecycleListener(new Tomcat.FixContextListener());
child.setPath("/cloudfoundryapplication");
ServletContainerInitializer initializer = getServletContextInitializer(
getContextPath());
child.addServletContainerInitializer(initializer, Collections.emptySet());
child.setCrossContext(true);
host.addChild(child);
}
};
}
private ServletContainerInitializer getServletContextInitializer(String contextPath) {
return (c, context) -> {
Servlet servlet = new GenericServlet() {
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
ServletContext context = req.getServletContext()
.getContext(contextPath);
context.getRequestDispatcher("/cloudfoundryapplication").forward(req,
res);
}
};
context.addServlet("cloudfoundry", servlet).addMapping("/*");
};
}